#include "choosefriendwidget.h"

/////////////////////////////////////
// 选择好友的窗口中的一个好友项
/////////////////////////////////////
ChooseFriendItem::ChooseFriendItem(ChooseFriendWidget *owner, const QString &userId, const QIcon &avatar, const QString &name, bool checked)
    :_owner(owner), _userId(userId)
{
    // 设置基本属性
    this->setFixedHeight(50);
    this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);

    // 创建布局管理器
    QHBoxLayout *layout = new QHBoxLayout();
    layout->setSpacing(10);
    layout->setContentsMargins(20, 0, 20, 0);
    this->setLayout(layout);

    // 创建复选框
    _checkBox = new QCheckBox();
    _checkBox->setChecked(checked);
    _checkBox->setFixedSize(25, 25);
    QString style = "QCheckBox { background-color: transparent; } QCheckBox::indicator { width: 20px; height: 20px; image: url(:/resource/image/unchecked.png); }";
    style += "QCheckBox::indicator:checked { image: url(:/resource/image/checked.png); }";
    _checkBox->setStyleSheet(style);

    // 创建头像
    _avatarBtn = new QPushButton();
    _avatarBtn->setFixedSize(40, 40);
    _avatarBtn->setIconSize(QSize(40, 40));
    _avatarBtn->setIcon(avatar);
    _avatarBtn->setStyleSheet("QPushButton { background-color: transparent; }");

    // 创建昵称
    _nameLabel = new QLabel();
    _nameLabel->setText(name);
    _nameLabel->setStyleSheet("QLabel { background-color: transparent; }");

    // 添加到布局管理器中
    layout->addWidget(_checkBox);
    layout->addWidget(_avatarBtn);
    layout->addWidget(_nameLabel);

    connect(_checkBox, &QCheckBox::toggled, this, [=](bool checked){
        if (checked)
        {
            _owner->addSelectFriend(_userId, avatar, name);
        }
        else
        {
            _owner->deleteSelectFriend(_userId);
        }
    });
}

void ChooseFriendItem::paintEvent(QPaintEvent *ev)
{
    QPainter painter(this);
    QPainterPath path;
    path.addRect(this->rect());
    if (_isHover)
    {
        painter.fillPath(path, QColor(230, 230, 230));
    }
    else
    {
        painter.fillPath(path, QColor(255, 255, 255));
    }
}

void ChooseFriendItem::enterEvent(QEnterEvent *ev)
{
    _isHover = true;
    this->update();
}

void ChooseFriendItem::leaveEvent(QEvent *ev)
{
    _isHover = false;
    this->update();
}

/////////////////////////////////////
// 选择好友的窗口
/////////////////////////////////////
ChooseFriendWidget::ChooseFriendWidget(QWidget *parent)
    :QDialog(parent)
{
    // 设置基本属性
    this->setWindowTitle("选择好友");
    this->setWindowIcon(QIcon(":/resource/image/logo.png"));
    this->setFixedSize(750, 550);
    this->setStyleSheet("QWidget { background-color: rgb(255, 255, 255); }");
    this->setAttribute(Qt::WA_DeleteOnClose);

    // 创建布局管理器
    QHBoxLayout *layout = new QHBoxLayout();
    layout->setSpacing(0);
    layout->setContentsMargins(0, 0, 0, 0);
    this->setLayout(layout);

    // 初始化左边列表
    initLeft(layout);
    // 初始化右边列表
    initRight(layout);
}

void ChooseFriendWidget::initLeft(QHBoxLayout *layout)
{
    // 创建滚动区域
    QScrollArea *scrollArea = new QScrollArea();
    scrollArea->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    scrollArea->setWidgetResizable(true);
    scrollArea->horizontalScrollBar()->setStyleSheet("QScrollBar:horizontal { height: 0px; }");
    scrollArea->verticalScrollBar()->setStyleSheet("QScrollBar:vertical { width: 2px; background-color: rgb(255, 255, 255); }");

    // 将totalwidget添加到滚动区域中
    _totalContainer = new QWidget();
    _totalContainer->setObjectName("totalContainer");
    _totalContainer->setStyleSheet("#totalContainer { background-color: rgb(255, 255, 255); }");
    scrollArea->setWidget(_totalContainer);

    // 给totalwidget添加布局管理器
    QVBoxLayout *vlayout = new QVBoxLayout();
    vlayout->setSpacing(0);
    vlayout->setContentsMargins(0, 0, 0, 0);
    vlayout->setAlignment(Qt::AlignTop);
    _totalContainer->setLayout(vlayout);

    // 添加到layout中
    layout->addWidget(scrollArea, 1);

#if TEST_UI
    for (int i = 0; i < 30; i++)
    {
        addFriend(QString::number(i), QIcon(":/resource/image/defaultAvatar.png"), "张三" + QString::number(i));
    }
#endif
}

void ChooseFriendWidget::initRight(QHBoxLayout *layout)
{
    // 创建布局管理器
    QGridLayout *glayout = new QGridLayout();
    glayout->setSpacing(10);
    glayout->setContentsMargins(20, 20, 20, 20);
    layout->addLayout(glayout, 1);

    // 创建提示label
    QLabel *tipLabel = new QLabel();
    tipLabel->setText("选择好友");
    tipLabel->setFixedHeight(30);
    tipLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    tipLabel->setAlignment(Qt::AlignLeft);
    tipLabel->setStyleSheet("QLabel { font-size: 16px; font-weight: 700; }");

    // 创建滚动区域
    QScrollArea *scrollArea = new QScrollArea();
    scrollArea->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    scrollArea->setWidgetResizable(true);
    scrollArea->setStyleSheet("QScrollArea { border: none; }");
    scrollArea->horizontalScrollBar()->setStyleSheet("QScrollBar:horizontal { height: 0px; }");
    scrollArea->verticalScrollBar()->setStyleSheet("QScrollBar:vertical { width: 2px; background-color: rgb(255, 255, 255); }");

    // 创建滚动区域中的choosewidget
    _chooseContainer = new QWidget();
    _chooseContainer->setObjectName("chooseContainer");
    _chooseContainer->setStyleSheet("#chooseContainer { background-color: rgb(255, 255, 255); }");
    scrollArea->setWidget(_chooseContainer);

    // 创建choosewidget中的垂直布局
    QVBoxLayout *vlayout = new QVBoxLayout();
    vlayout->setSpacing(0);
    vlayout->setContentsMargins(0, 0, 0, 0);
    vlayout->setAlignment(Qt::AlignTop);
    _chooseContainer->setLayout(vlayout);

    // 创建底部按钮
    QString style = "QPushButton { color: rgb(7, 191, 96); background-color: rgb(240, 240, 240); border: none; border-radius: 5px; }";
    style += "QPushButton:hover { background-color: rgb(220, 220, 220); } QPushButton:pressed { background-color: rgb(200, 200, 200); }";

    QPushButton *okBtn = new QPushButton();
    okBtn->setFixedHeight(40);
    okBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    okBtn->setText("完成");
    okBtn->setStyleSheet(style);

    QPushButton *cancelBtn = new QPushButton();
    cancelBtn->setFixedHeight(40);
    cancelBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    cancelBtn->setText("取消");
    cancelBtn->setStyleSheet(style);

    // 将控件添加到布局中
    glayout->addWidget(tipLabel, 0, 0, 1, 9);
    glayout->addWidget(scrollArea, 1, 0, 1, 9);
    glayout->addWidget(okBtn, 2, 1, 1, 3);
    glayout->addWidget(cancelBtn, 2, 5, 1, 3);

#if TEST_UI
    // for (int i = 0; i < 30; i++)
    // {
    //     addSelectFriend(QIcon(":/resource/image/defaultAvatar.png"), "张三" + QString::number(i));
    // }
#endif
}

void ChooseFriendWidget::addFriend(const QString &userId, const QIcon &avatar, const QString &name, bool checked)
{
    ChooseFriendItem *item = new ChooseFriendItem(this, userId, avatar, name, checked);
    _totalContainer->layout()->addWidget(item);
}

void ChooseFriendWidget::addSelectFriend(const QString &userId, const QIcon &avatar, const QString &name)
{
    ChooseFriendItem *item = new ChooseFriendItem(this, userId, avatar, name, true);
    _chooseContainer->layout()->addWidget(item);
}

void ChooseFriendWidget::deleteSelectFriend(const QString &userId)
{
    // 遍历 selectedContainer 中的每个 Item, 对比每个 Item 里的 userId , 是否是要删除的 userId.
    QVBoxLayout* vlayout = dynamic_cast<QVBoxLayout*>(_chooseContainer->layout());
    // 由于是要 "遍历" + "删除" 需要从后往前进行
    for (int i = vlayout->count() - 1; i >= 0; --i) {
        auto* item = vlayout->itemAt(i);
        if (item == nullptr || item->widget() == nullptr) {
            continue;
        }
        ChooseFriendItem* chooseFriendItem = dynamic_cast<ChooseFriendItem*>(item->widget());
        // 判定当前的 Item 的 userId 是否是要删除的 userId
        if (chooseFriendItem->getUserId() != userId) {
            continue;
        }
        vlayout->removeWidget(chooseFriendItem);
        // 此处直接使用 delete 可能导致程序直接崩溃. 因为 delete 该对象的时候, 该对象内部的 QCheckBox 还在使用中 (触发着信号槽呢)
        // 改成 deleteLater, 就相当于把 delete 操作委托给 Qt 自身来完成了. 告诉 Qt 框架说, 你要删除这个对象. 至于啥时候删除 Qt
        // 会确保在 Qt 自身用完了之后, 去真正删除.
        // delete chooseFriendItem;
        chooseFriendItem->deleteLater();
        break;
    }

    // 再遍历一下左侧列表, 把左侧列表中对应 item 的 checkBox 勾选状态取消掉.
    QVBoxLayout* vlayoutLeft = dynamic_cast<QVBoxLayout*>(_totalContainer->layout());
    for (int i = 0; i < vlayoutLeft->count(); i++) {
        auto* item = vlayoutLeft->itemAt(i);
        if (item == nullptr || item->widget() == nullptr) {
            continue;
        }
        ChooseFriendItem* chooseFriendItem = dynamic_cast<ChooseFriendItem*>(item->widget());
        if (chooseFriendItem->getUserId() != userId) {
            continue;
        }
        // 取消 checkBox 选中状态
        chooseFriendItem->getCheckBox()->setChecked(false);
        break;
    }
}
